﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.Collections.ObjectModel;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using System.Threading;
using System.Data.Entity;
using Wicresoft.TFSAutoNotify.Common;

namespace TFSAutoNotify.WindowsService
{
   public class AutoNotify
    {
        static Tfs_AutoNotifyEntities tfsDB = new Tfs_AutoNotifyEntities();
        public static void Notify()
        {
            Uri configurationServerUri = new Uri("http://ws-fs-01:8080/tfs/MyLab");
            List<RegisteredProjectCollection> projectCollections;
            TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);
            projectCollections = new List<RegisteredProjectCollection> { RegisteredTfsConnections.GetProjectCollection(configurationServerUri) };
            var registeredProjectCollection = projectCollections[0];
            var projectCollection =
                TfsTeamProjectCollectionFactory.GetTeamProjectCollection(registeredProjectCollection);

            try
            {
                //var versionControl = (VersionControlServer)projectCollection.GetService(typeof(VersionControlServer));
                var versionControl = projectCollection.GetService<VersionControlServer>();

                var teamProjects = new List<TeamProject>(versionControl.GetAllTeamProjects(false));
                //for (int i = 0; i < teamProjects.Count; i++)
                //{
                //    Console.WriteLine(teamProjects[i].Name);
                //}

                Shelveset[] shelveSet =
                versionControl.QueryShelvesets("", "");
                WriteLog("nidlfsaflsadjlfsadjflasdjflsaf");
                SaveShelveSet(shelveSet);
                DeleteShelveSetIfMoreThan(shelveSet, versionControl, 1);
            }
            finally
            {

            }
            Console.Write(".");
        }
        public static void DeleteShelveSetIfMoreThan(Shelveset[] sets, VersionControlServer server, int timeMonth)
        {
            foreach (Shelveset s in sets)
            {
                DateTime x = System.DateTime.Now.AddMonths(-timeMonth);
                if (s.CreationDate <= x)
                {
                    server.DeleteShelveset(s);
                }
            }
        }
        public static void SaveShelveSet(Shelveset[] sets)
        {


            foreach (Shelveset s in sets)
            {
                if (!IsExist(s.Name, tfsDB.ShelveInfos.ToList()))
                {
                    ShelveInfo _shelve = CreateShelveInfo(s);
                    tfsDB.ShelveInfos.Add(_shelve);
                    tfsDB.SaveChanges();

                }
                if (tfsDB.ShelveInfos.ToList().Count == 0)
                {
                    ShelveInfo _shelve = CreateShelveInfo(s);
                    tfsDB.ShelveInfos.Add(_shelve);
                    tfsDB.SaveChanges();
                }

            }

        }
        public static ShelveInfo CreateShelveInfo(Shelveset s)
        {
            ShelveInfo _sheleve = new ShelveInfo();
            string itemInfor = "";

            foreach (var x in s.WorkItemInfo)
            {
                var _x = x.WorkItem;
                itemInfor = itemInfor + "Id:" + _x.Id + "Title:" + _x.Title + ",";
            }
            itemInfor = itemInfor + "\n";
            string codeReviewer = s.CheckinNote.Values.First(p => p.Name == "Code Reviewer").Value;
            string setStr = " Shelve Name: " + s.Name
                + "\n Owner: " + s.OwnerName
                + "\n Code Reviewer:" + codeReviewer
                + "\n Related WorkItem:" + itemInfor
                + "\n Description:" + s.Comment;

            string template = @"Hi {0}, 

I have a shelve set which needs your code review. Please help to review it and give your feedback.

Owner:                                {1}
Code reviewer:                        {2}
Work item:                            {3}
Description:                          {4}

Thanks
ws-fs-01
{5}";
            string body = string.Format(template, codeReviewer, s.OwnerName, codeReviewer, itemInfor, s.Comment, s.OwnerName);
            _sheleve.Title = s.Name;
            _sheleve.Owner = s.OwnerName;
            _sheleve.CreateTime = s.CreationDate;
            _sheleve.IsSent = false;
            _sheleve.SentTime = DateTime.MaxValue;
            _sheleve.MailFrom = Properties.Settings.Default.TFSEmail;
            _sheleve.MailTo = queryMailTo(codeReviewer);
            _sheleve.CC = Properties.Settings.Default.CC;
            _sheleve.BCC = Properties.Settings.Default.BCC;
            _sheleve.Subject = "ShelveSet:" + s.Name + " Code Review Request From " + s.OwnerName;
            _sheleve.Body = body;
            return _sheleve;
        }
        public static bool IsExist(string _info, List<ShelveInfo> _list)
        {
            bool y = false;
            foreach (ShelveInfo x in _list)
            {
                if (x.Title.Equals(_info))
                {
                    y = true;
                }

            }
            return y;
        }
        public static string queryMailTo(string codeReviewer)
        {
            string email = "";
            var employeesInfo = tfsDB.EmployeesInfos.ToList();
            foreach (var x in employeesInfo)
            {
                if (IsWho(x, codeReviewer))
                {
                    email = x.Email;
                }
            }
            return email;
        }
        public static bool IsWho(EmployeesInfo p, string codeReviewers)
        {
            bool x = false;
            string codeReviewer = codeReviewers.Trim();
            if (p.EnglishName.Equals(codeReviewer, StringComparison.OrdinalIgnoreCase))
            {
                x = true;
            }
            if (p.PinYin.ToLower().Contains(codeReviewer.ToLower()))
            {
                x = true;
            }
            if (p.Name.Contains(codeReviewer))
            {
                x = true;
            }
            return x;
        }

        public static bool IsExist(string info, string owner, DateTime createTime)
        {

            return tfsDB.ShelveInfos.Count(p => p.Title == info && p.CreateTime == createTime && p.Owner == owner) >= 1;


        }
        public static void WriteLog(string x)
        {
            File.AppendAllText(@"d:\info\1.txt", x);
           
        }

    }
}

